package com.zh;

/**
 * Created by zhaohui on 2019/9/9
 * Description:
 */
public abstract class Example {

    /**
     * 对数组排序
     * @param a
     */
    public abstract void sort(Comparable[] a);

    /**
     * 判断第一个元素是否小于第二个元素
     * @param v
     * @param w
     * @return
     */
    public boolean less(Comparable v, Comparable w) {
        return v.compareTo(w) < 0;
    }

    /**
     * 交换数组中两个元素的位置
     * @param a
     * @param i
     * @param j
     */
    public void exch(Comparable[] a, int i, int j) {
        Comparable t = a[i];
        a[i] = a[j];
        a[j] = t;
    }

    /**
     * 打印数组
     * @param a
     */
    public void show(Comparable[] a) {
        for (int i = 0; i < a.length; i++)
            System.out.print(a[i] + " ");
        System.out.println();
    }

    /**
     * 判断数组是否已经排好序
     * @param a
     * @return
     */
    public boolean isSorted(Comparable[] a) {
        for (int i = 1; i < a.length; i++) {
            if (less(a[i], a[i-1]))
                return false;
        }
        return true;
    }

    /**
     * 测试排序效果
     */
    public void test() {
        Integer[] a = new Integer[]{1, 4, 5, 2, 9, 3};
        System.out.println("原始数组：");
        show(a);
        System.out.println("数组是否有序");
        System.out.println(isSorted(a));
        sort(a);
        System.out.println("排序后数组：");
        show(a);
        System.out.println("数组是否有序");
        System.out.println(isSorted(a));
    }

}
